package com.flyiu.data.consistency.context;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.flyiu.data.consistency.model.DistributedTransactionInstance;
import com.flyiu.data.consistency.model.DistributedTransactionState;
import com.flyiu.data.consistency.repository.DistributedTransactionInstanceRepository;

@Component
public class DistributedTransactionScheduledQueue {

	private static ConcurrentLinkedQueue<DistributedTransactionInstance> queue = new ConcurrentLinkedQueue<>();
	
	@Autowired
	private DistributedTransactionInstanceRepository instanceRepository;
	
	/**
	 * 添加队列
	 * @param e
	 */
	public static void add(DistributedTransactionInstance e){
		queue.add(e);
	}
	
	/**
	 * 获取队列
	 * @param size
	 * @return
	 */
	public List<DistributedTransactionInstance> get(int size){
		List<DistributedTransactionInstance> instanceList = new LinkedList<>();
		
		for (int i = 0; i < size; i++) {
			DistributedTransactionInstance instance =  queue.poll();
			if(instance!=null){
				instanceList.add(instance);
			}
		}
		return instanceList;
		
	}
	
	/**
	 * 每一秒更新一次次分布式事务状态
	 */
	@Scheduled(fixedRate = 1000)
	public void exe(){
		List<Long> ids = get(500).stream().map(DistributedTransactionInstance::getId).collect(Collectors.toList());
		if(ids.isEmpty()){
			return;
		}
		instanceRepository.changeStatus(DistributedTransactionState.COMMIT, ids);
	}
}
